import { resourceEntApi } from '@/api';
import { pageOpeTypeEnum } from '@/common';
import YmCollaPanes from '@/components/YmCollaPanes';
import { useAppSelector } from '@/redux/store';
import { combineImgs, convertBase64UrlToBlob, pdfTransformToImgs } from '@/utils/pdfAndImg';
import { Button, Col, Form, Input, message, Row, Upload } from 'antd';
import * as pdfjsLib from 'pdfjs-dist';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { v4 as uuid } from 'uuid';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';

const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};
const { PaneItem } = YmAddPageLayout;

export interface IImg {
  src: string;
  width: number;
  height: number;
}
const plantType = process.env.processEnvDetail.REACT_APP_PLATFORM;
function AddPdfCourseWare() {
  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const type = searchParam.get('type');
  const parentId = searchParam.get('parentId');
  const { entId } = useAppSelector((state) => state.loginEnt);
  const coursewareId = searchParam.get('resourceId');
  const [form] = Form.useForm();
  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });

  // 使用aliyunoss进行操作
  const customRequest = useYmAliOss();

  useEffect(() => {
    if (type === pageOpeTypeEnum['edit'] && coursewareId) {
      resourceEntApi.getCourseWareById({ coursewareId }).then((res: any) => {
        const {
          data: { name, picUrl, picTextContent },
        } = res;
        let tempPictextContent;
        try {
          tempPictextContent = JSON.parse(picTextContent);
        } catch (err) {
          console.log('--AddPdfCourseWar--pictextContent--parse错误--', err);
        }

        form.setFieldsValue({
          name,
          picUrl: [{ uid: uuid(), url: picUrl }],
          pictextContent: [{ name: tempPictextContent?.name || '', url: tempPictextContent?.url || '', uid: uuid() }],
        });
      });
    }
  }, [coursewareId, form, type]);

  const goBackToList = () => {
    const x = plantType === 'boss' ? '/resourceLibrary/' : '/cusResLib/';
    navigator(x + 'courseWare', { state: { activeTab: 'pdfCourseWare' } });
  };

  const _formSub = (subType: number) => {
    setLoadingDetail({ subBtnDis: true, viewLoading: true });
    form
      .validateFields()
      .then((values) => {
        const { name, picUrl, pictextContent } = values;
        console.log('--addPdfCourseWare--values--:', values);
        const fileName = pictextContent[0].name;
        const ext = fileName.split('.').pop() || 'jpg';
        const newName = fileName.replace(ext, '') + 'pfd';

        const tempPictextContent = JSON.stringify({ url: pictextContent[0].response, name: newName, type: 'pdf' });

        const subData: any = {
          type: '400',
          entId,
          picTextContent: tempPictextContent,
          name,
          picUrl: picUrl[0].response,
          // pictextContent: tempPictextContent,
          parentId,
          // coursewareType: 'pdf',
        };
        console.log('--addPdfCourseWare--subData--:', subData);
        let requestApi;
        if (type === pageOpeTypeEnum['add']) {
          requestApi = resourceEntApi.createCourseWare(subData);
        } else if (type === pageOpeTypeEnum['edit']) {
          if (plantType === 'boss') subData.coursewareId = coursewareId;
          else subData.guid = coursewareId;
          requestApi = resourceEntApi.updateCourseWare(subData);
        } else {
          return message.error('type 未定义');
        }
        requestApi
          .then((res: any) => {
            const { code, msg } = res;
            if (code === '200') {
              message.success(msg || `${type === pageOpeTypeEnum['add'] ? '添加' : '编辑'}成功`);
              if (subType === 1) {
                //保存
                goBackToList();
              } else {
                //保存并继续
                form.resetFields();
              }
            } else {
              message.error(msg);
            }
          })
          .catch((err: any) => {
            console.log('--addPdfCourseWare--_formSub--err--:', err);
          })
          .finally(() => {
            setLoadingDetail({ subBtnDis: false, viewLoading: false });
          });
      })
      .catch((err) => {
        setLoadingDetail({ subBtnDis: false, viewLoading: false });
      });
  };
  // 保存
  const sub = () => {
    _formSub(1);
  };

  // 保存并继续添加
  const subAndContinue = () => {
    _formSub(2);
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOnce" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={sub}>
        保存
      </Button>,
      <Button key="subContinue" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={subAndContinue}>
        保存并继续添加
      </Button>,
    ];
    switch (type) {
      case pageOpeTypeEnum['add']:
        return operationBtn;
      case pageOpeTypeEnum['edit']:
        return operationBtn.slice(0, 1); //substring from to
    }
  }, [type, loadingDetail]);

  // pdf 转成图片
  const pdfTransformToImg = (file: File, fileList: File[]): Promise<File | Blob | string> => {
    setLoadingDetail({ subBtnDis: true, viewLoading: true });
    //1.获取上传的pdf文件
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const fileBase64: any = reader.result;
        const code = fileBase64 && fileBase64.split(',')[1];
        if (!code) {
          setLoadingDetail({ subBtnDis: false, viewLoading: false });
          resolve(Upload.LIST_IGNORE);
          return message.error('文件格式错误');
        }
        // 2.pdf转成bolob对象
        const blobCode = window.atob(code);
        pdfjsLib.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry.js');
        pdfjsLib
          .getDocument({ data: blobCode })
          .promise.then((pdf) => {
            // console.log('--pdf---:', pdf);
            //获取pdf的每一页并转成img
            pdfTransformToImgs(pdf, 35)
              .then((imgBase64Arrays) => {
                // 把所有的图片合成一张图片
                combineImgs(imgBase64Arrays).then((combineImgBase64Code) => {
                  // console.log('---newImgSrc--combineImgBase64Code--:', combineImgBase64Code);
                  const imgBlob = convertBase64UrlToBlob(combineImgBase64Code);
                  const fileName = file.name;
                  const ext = fileName.split('.').pop() || 'pfd';
                  const newName = fileName.replace(ext, '') + 'jpg';
                  if (!form.getFieldsValue().name) {
                    const values = form.getFieldsValue();
                    values.name = newName.substring(0, newName.length - 4).substring(0, 18);
                    form.setFieldsValue(values);
                  }
                  const newFile = new File([imgBlob], newName);
                  setLoadingDetail({ subBtnDis: false, viewLoading: false });
                  resolve(newFile);
                });
              })
              .catch((errMag) => {
                message.error(errMag);
                resolve(Upload.LIST_IGNORE);
              });

            // 不上传
            // reject(Upload.LIST_IGNORE);  // reject不行
            // resolve(Upload.LIST_IGNORE);
          })
          .catch((err: any) => {
            setLoadingDetail({ subBtnDis: false, viewLoading: false });
            console.log('--pdfjsLib--err--:', err);
            resolve(Upload.LIST_IGNORE);
          });
      };
    });
  };
  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          goBackToList();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );
  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={(type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + 'pdf课件'}
        className="pane_tab1"
      >
        <YmCollaPanes collapsible={false} headerTitle={<div></div>} paneKey={1} collPanesActiveKeys={[1]}>
          <Form layout="horizontal" labelAlign="right" size="middle" form={form}>
            <Row>
              <Col span={24}>
                <Form.Item label="封面图" required>
                  <Form.Item name="picUrl" noStyle rules={YmUpload.formRules('请上传课件封面图')}>
                    <YmUpload
                      maxCount={1}
                      cardWidth={140}
                      cardHeight={140}
                      accept="image/*"
                      customRequest={customRequest}
                    >
                      上传图片
                    </YmUpload>
                  </Form.Item>
                  <p className="safe-edu_upload_warning">图片宽高比例以1.875:1为宜，如：750*400</p>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item label="pdf文件" required>
                  <Form.Item name="pictextContent" noStyle rules={requireRules('请上传课件文件')}>
                    <YmUpload
                      maxCount={1}
                      accept=".pdf"
                      acceptExt="pdf"
                      listType="info-list"
                      beforeUpload={pdfTransformToImg}
                      customRequest={customRequest}
                    >
                      上传文件
                    </YmUpload>
                  </Form.Item>
                  <p className="safe-edu_upload_warning">请上传pdf格式文件，最多可上传35页</p>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="name" label="名称" rules={requireRules('请输入课件名称')}>
                  <Input
                    placeholder="请输入"
                    autoComplete="off"
                    maxLength={18}
                    showCount
                    style={{ maxWidth: '300px' }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </YmCollaPanes>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default AddPdfCourseWare;
